package com.hd.manager.config;

import com.hd.hdxgddcommon.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)//控制过滤器的级别
public class CorsFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        String origin = request.getHeader("Origin");
        if (StringUtils.isNotBlank(origin)) {
            //   log.debug("允许域名:[{}]跨域访问... 路径[{}]", origin, IPUtils.getRealIp(request));
            response.addHeader("Access-Control-Allow-Origin", origin);//允许这个域名可以跨域
            response.addHeader("Access-Control-Allow-Credentials", "true");//允许携带cookie
            response.setHeader("Access-Control-Allow-Headers", "Content-Type,x-requested-with,token");//允许携带的请求头
            response.setHeader("Access-Control-Allow-Methods", "OPTIONS, GET, PUT, POST, DELETE");//支持的请求方法
            if (request.getMethod().equals(RequestMethod.OPTIONS.name())) {
                response.setStatus(200);
                response.setHeader("Access-Control-Max-Age", "86400");//如果是预检请求，设置一个有效期，在有效期内就不会再有预检请求了
                return;
            }
        }
        filterChain.doFilter(request, response);
    }

}